/** @jsxImportSource @emotion/react */
import * as React from "react";
import {PreloadedQuery, usePreloadedQuery} from "react-relay/hooks";
import {ReportStarter} from "./ReportStarter";
import {ViewReportMainQuery} from "./__generated__/ViewReportMainQuery.graphql";
import {EditStorageContext, useEditStorageContext} from "./StorageContext";
import {DeviceList} from "../device/DeviceList";
import {
    Button,
    IconArrowLeft, IconArrowRight,
    IconButton,
    IconCloud, IconPackage,
    MenuItem,
    MenuList,
    TwoHalfRightPanel, useMMenuBarOcup, useTheme, useToast
} from "customize-easy-ui-component";
import {Link as RouterLink} from "../routing/Link";
import {DeviceDetail} from "../device/DeviceDetail";
import useMutation from 'use-mutation';
// import {string} from "prop-types";
import {usePrintPdf} from "../hooks/usePrintPdf";
import {ConfigRoot, FileTransform} from "page2pdf_server/src/types/request/config";
import queryString from "query-string";
import {useContext} from "react";
import RoutingContext from "../routing/RoutingContext";

const graphql = require("babel-plugin-relay/macro");

//模板的版本号和相应代码维护管理是个问题；不是下载离线的，而是时刻web在线的文档格式；配套数据库数据加上配套模板才能拼凑出正式文档。要保留维护几年？有人还在用旧的。
//模板类型：支持主报告类型1个+分报告类型多个的情况，报告展示入口管理。模板版本号由后端管理。


interface ViewReportMainProps {
    prepared: {
        template: any;   //该类型的模板 主入口：
        query: PreloadedQuery<ViewReportMainQuery>;
    }
    routeData: any;
}
/**正式报告 预览 打印 全页面 没带编辑器的：
* */
export default function ViewReportMain( {
               prepared:{
                   template: LibofLoadable, query: myQuery
               },
               routeData
         }:  ViewReportMainProps
) {
    const qs= queryString.parse(window.location.search);
    const printing =qs && !!qs.print;
    //确保动态加载 前端源代码的 成功
/*    const module= template.read();
        //不同版本号的模板组件入口不一样。
    const reportNode= module.reportTemplate[routeData.params.verId];
    if(!reportNode) {
        throw new Error(`没有${routeData.params.template}类型${routeData.params.verId}版本的报告模板`);
    }*/

    const data = usePreloadedQuery<ViewReportMainQuery>(
        graphql`
            query ViewReportMainQuery($id: ID! ) {
                getReport(id: $id) {
                    id
                    data
                    snapshot
                    modeltype,modelversion
                    isp{id, no}
                    ...ReportStarterIsp
                }
            }
        `,
        myQuery,
    );
    const { getReport: items }=data;

    const theme = useTheme();
    const repContext = useEditStorageContext({});
    //工具条高度采用与底下的主菜单条的高度一样的设置
    const { barHeight }= useMMenuBarOcup(false);
    const { history } = useContext(RoutingContext);
    const urlPrintV=`/reportView/${items?.modeltype}/ver/${items?.modelversion}/`+ items?.id+'?print=1';
    //组装正式报告：可能有多个子报告和目录及封面的，拼装一份pdf;       【全部展开显示的报告】?print=1
    function newJob() {
        const urlouter=`${process.env.REACT_APP_WEB}`+ urlPrintV;
        const job = {
            name: "报告-" + (items?.isp?.no || '默认报告号的'),
            singleTab: true,
            lay: {
                head: [
                    '<div style=\\"position: relative; width:100%; text-align:center; border-bottom: 1pt solid #eeeeee; margin: 3.5mm 0px 10px; font-size: 8pt\\"></span>',
                    '<div style=\\"position: absolute; width:100%; text-align: center; bottom: 5px;\\"><span id=\\"titlespan\\" class=title></div>',
                    '<div style=\\"-NOT_DISPLAY- position: absolute; text-align: right; bottom: 5px;right: 20px;\\">',
                    "<span>${pageNumber}</span> / <span>${totalPages}</span></div>",
                    "</div>",
                ],
                foot: [
                    '<div style=\\"position: relative; width: 100%; text-align: left; border-top: 1pt solid #eeeeee; margin:  10px 0px 1.5mm; font-size: 8pt;\\">',
                    '<div style=\\"position: absolute; text-align: left; top: 5px;left: 60px;\\">YYYY-MM-DD</div>',
                    '<div style=\\"position: absolute; width: 100%; text-align: center; top: 5px;\\">&copy;2022 ABCD</div>',
                    '<div style=\\"-NOT_DISPLAY- position: absolute; text-align: right;top: 5px;right: 20px;\\"> <span>${pageNumber}</span> / <span>${totalPages}</span></div>',
                    "</div>",
                ],
            },
            files: [
                {
                    url: urlouter,
                    out: "testHtmlPrint转",
                    headFrom: 2,
                    frNo: 2,
                },
            ],
        } as unknown as ConfigRoot<FileTransform>;

        return job;
    }
    const [handleSubmit] = usePrintPdf(newJob);
/* 底下的( { reportTemplate } :any) => {函数的 reportTemplate 实际来自xxx.E.tsx文件的：动态加载。
        export  const  reportTemplate={
          "1": <ReportView source={null} verId={'1'}/>,
        };
* */
    //ViewReportMain 811px 滚动条晃动，
  return (
    <div className={'ViewReportMain'} css={{
        background: "white",
        "@media not print": {
            marginBottom: `${barHeight}`,
        }
      }}
    >
          <EditStorageContext.Provider
              value={repContext}
          >
              <LibofLoadable fallback={<h1>没模板主入口</h1>} >
                  {
                      ( { reportTemplate } :any) => {
                          const reportNode= reportTemplate[routeData.params.verId];
                          if(!reportNode) {
                              throw new Error(`没有${routeData.params.template}类型${routeData.params.verId}版本的报告模板`);
                          }
                          return (
                              <ViewReportMainInner items={items} reportNode={reportNode} routeData={routeData} />
                          );
                      }
                  }
              </LibofLoadable>
          </EditStorageContext.Provider>

        <div css={{
            "@media not print": {
                marginTop: '0.5rem',        //影响打印的，多出了空白页！
            },
            "@media print": {
                display: 'none'
            },
        }}>
            <Button  intent="primary"
                     onPress={(e) => { handleSubmit!();
                     }}
            >送打印转换器转PDF
            </Button>
            {!printing && <Button intent="primary" css={{marginLeft: theme.spaces.sm}}
                              onPress={async () => {
                                  history.push(urlPrintV);
                              }}>打印预览(全展开)
                </Button>
            }
        </div>
    </div>
  );
}
interface ViewReportMainInnerProps {
    items:any;
    reportNode:any;
    routeData:any;
}
//打印模式报告，全页面，没带编辑器的。
function ViewReportMainInner( {items, reportNode, routeData} :ViewReportMainInnerProps
) {
    //打印预览正式报告： 也需要EditStorageContext？多此一举。 下一级通用组件ReportStarter要求。
    const source =React.useMemo(() => {
        const  dat =items&&items.data&&JSON.parse(items.data);
        const  snap =items&&items.snapshot&&JSON.parse(items.snapshot);
        if(snap)  return dat && {...dat, ...snap};
        else return dat;
    }, [items]);
    // console.log("ViewReportMainInner层路由DDitems=",items,"storage",storage);
    //实际ReportStarter不依赖于EditStorageContext的，可以去掉setStorage
    return (
        <React.Fragment>
            {
                source && <ReportStarter id={routeData.params.repId!} source={source} template={reportNode} items={items}/>
            }
        </React.Fragment>
    );
}

// export default ViewReportMain;
